<template>
    <BPTable ref='tableRef' align='center' row-key='id' name-key='cardNo' :columns='columns' :api='pageApi' :buttons='buttons'>

        <template #status="{record}">
            <a-tag :color="record.status == 1 ? 'success' : ''">{{ CHARGING_CARD_STATUS[record.status] }}</a-tag>
        </template>


        <!-- <template #$action="{record}">
            <RouterLink :to="'/chargingStation/' + record.id + '?name=' + record.name">
                <BTextButton>详情</BTextButton>
            </RouterLink>
        </template> -->
    </BPTable>
    <BDialog v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit' @close="resetForm">
        <a-form layout='horizontal"' ref='formRef' :label-col='{span : 5}' :model='formData'>
            <a-form-item style='display:none' name='id'>
                <a-input type='hidden' v-model:value='formData.id' />
            </a-form-item>
            <a-form-item v-if="formData.id" label="卡号" name="cardNo" required>
                <a-input v-model:value='formData.cardNo' />
            </a-form-item>
            <a-form-item v-else label="卡号" name="cardNos" required>
                <a-textarea v-model:value='formData.cardNos' placeholder="一行一个卡号，最多100个卡号" />
            </a-form-item>
            <a-form-item label="备注" name="remark">
                <a-textarea v-model:value='formData.remark' />
            </a-form-item>
        </a-form>

        <div v-if="showError" style="color: red;">
            以下卡号已经存在：{{ existsCardNos }}
        </div>

    </BDialog>
</template>

<script lang='ts' setup>
    import { ref } from "vue";
    import { message, Modal } from "ant-design-vue";
    import { deleteApi, pageApi, saveApi } from "@/api/chargingCard";
    import { parseTime } from "@/utils";
    import { useI18nStore } from "@/store/i18n";
import { CHARGING_CARD_STATUS } from "@/constant";
    

    const visible = ref(false)
    const formRef = ref()
    const dialogTitle = ref()
    const tableRef = ref()
    const showError = ref(false)
    const existsCardNos = ref('')

    const i18n = useI18nStore()


    const buttons = ref<SearchButton[]>([])

    buttons.value.push({
        button : 'add',
        func : () => {
            dialogTitle.value = i18n.t('add')
            visible.value = true
        }
    })


    const formData = ref({
        id : 0,
        cardNo : '',
        cardNos : '',
        remark : '',
    })


    



    const columns = ref<Column[]>([
        {
            dataIndex : 'cardNo',
            title : '卡号',
            inSearch : true,
        },



        {
            dataIndex : 'status',
            title : '状态',
        },

        {
            dataIndex : 'remark',
            title : '备注',
        },

        {
            dataIndex : 'activeTime',
            title : '激活时间',
            align : 'center',
            customRender({text}) {
                return parseTime(text)
            }
        },

        {
            title : '创建时间',
            dataIndex : 'createTime',
            align : 'center',
            customRender({text}) {
                return parseTime(text)
            }
        },

        
        {
            dataIndex : '$action',
            title : i18n.t('operation'),
            align : 'center',
            $edit : (row) => {
                dialogTitle.value = i18n.t('update')
                for(let k in formData.value) {
                    if(row[k]) {
                        if(row[k] != undefined) {
                            formData.value[k] = row[k]
                        }
                    }
                    
                }

                visible.value = true
                
            },  

            $delete : async(row, index) => {
                const res = await deleteApi(row.id)
                if(res.success) {
                    tableRef.value.reload()
                    message.success(i18n.t('deleteSuccess'))
                }else {
                    message.error(res.msg)
                }
            }
            
        },
    ])



    function resetForm() {
        formData.value.cardNo = ''
        formData.value.cardNos = ''
        formRef.value.clearValidate()
        formRef.value.resetFields()
    }
    

    async function submit() {
        showError.value = false
        try {
            let {cardNos, cardNo, ...params}  = await formRef.value.validate()
            if(!params.id) {
                cardNos = cardNos.split('\n').filter(cardNo => cardNo.trim() !== '')
                if(cardNos.length == 0) {
                    message.error('请输入卡号')
                    return
                }

                if(cardNos.length > 100) {
                    message.error('最多100个卡号')
                    return
                }

                if(new Set(cardNos).size !== cardNos.length) {
                    message.error('有重复卡号')
                    return
                }

                params.cardNos = cardNos
            }else {
                params.cardNo = cardNo
            }
            
             
            const res = await saveApi(params)
            if(res.success) {
                tableRef.value.reload()
                message.success(i18n.t('saveSuccess'))
                resetForm()
                visible.value = false
            }else {
                console.log(res)
                if(res.code == -1) {
                    console.log(res.cardNos, res.cardNos.join)
                    existsCardNos.value = res.cardNos.join(',')
                    showError.value = true
                    return
                }
                Modal.error({
                    title : res.msg
                })
            }
        } catch (error) {
            console.log(error)
        }
    }


</script>

<style lang="scss" module>
    .addressSelect{
        display: flex;
        align-items: center;
        .input{
            flex: 1;
        }
    }

    .map{
        width: 100%;
        height: 500px;
    }
</style>